/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.glc.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.entity.glc.*;
import com.plian.system.entity.im.ProjectInfo;
import com.plian.system.entity.pf.*;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.enumeratea.BusinessIndicatorsStatus;
import com.plian.system.mapper.glc.GlcBaseBusinessIndicatorsMapper;
import com.plian.system.mapper.pf.BaseBusinessIndicatorsMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.glc.*;
import com.plian.system.service.glcRq.IGlcBaseBusinessIndicatorsRqService;
import com.plian.system.service.im.IProjectInfoService;
import com.plian.system.service.pf.*;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.glc.*;
import com.plian.system.vo.pf.BaseBusinessIndicatorsVO;
import com.plian.system.vo.pf.BusinessIndicatorsVO;
import com.plian.system.vo.pf.TaskIndicatorsVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.glc.*;
import com.plian.system.wrapper.pf.BaseBusinessIndicatorsWrapper;
import com.plian.system.wrapper.pf.BusinessIndicatorsWrapper;
import com.plian.system.wrapper.pf.TaskIndicatorsWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 经营业绩考核指标主表 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class GlcBaseBusinessIndicatorsServiceImpl extends BaseServiceImpl<BaseBusinessIndicatorsMapper, BaseBusinessIndicators> implements IGlcBaseBusinessIndicatorsService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private IBusinessIndicatorsService businessIndicatorsService;

	private ITaskIndicatorsService taskIndicatorsService;

	private IMajorProjectService majorProjectService;

	private IMainBusinessService mainBusinessService;

	private BaseBusinessIndicatorsWrapper baseBusinessIndicatorsWrapper;

	private BusinessIndicatorsWrapper businessIndicatorsWrapper;

	private TaskIndicatorsWrapper taskIndicatorsWrapper;

	private IOrgService orgService;

	private IAppraisalIndexService appraisalIndexService;

	private IProjectInfoService projectInfoService;

	private IApprovalMessageService approvalMessageService;
	private FileService fileService;

	@Override
	public boolean saveOrUpdate(BaseBusinessIndicators baseBusinessIndicators) {
		baseBusinessIndicators.setModuleType(2);//任期经营绩效类型
		if (!Optional.ofNullable(baseBusinessIndicators.getStatus()).isPresent()){
			baseBusinessIndicators.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (baseBusinessIndicators.getStatus().equals(FormStatusConstant.REJECT)){
			baseBusinessIndicators.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (!Optional.ofNullable(baseBusinessIndicators.getId()).isPresent()) {
			baseBusinessIndicators.setCode(formCodeService.getCode(FormTypeConstant.MANAGEMENT_PERFORMANCE));
			baseBusinessIndicators.setFormType(String.valueOf(FormTypeConstant.MANAGEMENT_PERFORMANCE));
			baseBusinessIndicators.setVersion(1);
		}

		return super.saveOrUpdate(baseBusinessIndicators);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			BaseBusinessIndicators baseBusinessIndicators = getById(id);
			if (baseBusinessIndicators == null) {
				return false;
			} else if (baseBusinessIndicators.getStatus() != null &&
					(baseBusinessIndicators.getStatus() != FormStatusConstant.STASH && baseBusinessIndicators.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}

		boolean result = super.deleteLogic(ids);
		if (result){
			businessIndicatorsService.deleteByParentId(ids);
			taskIndicatorsService.deleteByParentId(ids);
			majorProjectService.deleteByParentId(ids);
			mainBusinessService.deleteByParentId(ids);
		}

		return result;
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		BaseBusinessIndicators indicators = getById(id);
		indicators.setApprovedUser(TokenUtil.getTokenUserId());
		Date now = DateUtil.now();
		indicators.setApprovedTime(now);
		indicators.setIsLatest(2);
		indicators.setVersion(1);
		indicators.setInitialId(Long.valueOf(id));
		indicators.setIndicatorStatus(BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
		updateById(indicators);

		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
	}

	@Override
	public Boolean reject(String id, int formState,String comment) {
		return handleStatus(Long.valueOf(id), formState,comment);
	}

	@Override
	public String checkYear(BaseBusinessIndicators baseBusinessIndicators) {
		QueryWrapper<BaseBusinessIndicators> queryWrapper = new QueryWrapper<>();
		if (!Optional.ofNullable(baseBusinessIndicators.getFillingYear()).isPresent()) {
			return "填报时间为空";
		}
		if (!Optional.ofNullable(baseBusinessIndicators.getFillingUnitId()).isPresent()){
			return "填报单位为空";
		}
		queryWrapper.eq("staff_id",baseBusinessIndicators.getStaffId());
//		queryWrapper.eq("filling_unit_id",baseBusinessIndicators.getFillingUnitId());
		queryWrapper.eq("filling_year", baseBusinessIndicators.getFillingYear());
		queryWrapper.eq("module_type",2);
		List<BaseBusinessIndicators> list = list(queryWrapper);

		List<BusinessIndicators> businessIndicatorsList = baseBusinessIndicators.getBusinessIndicators();
		if (CollectionUtil.isNotEmpty(businessIndicatorsList)){
			for (BusinessIndicators indicators:businessIndicatorsList){
				BigDecimal weight = indicators.getIndicatorsWeight();
				if (weight.compareTo(BigDecimal.ZERO) < 0){
					return "指标权重不能为负数";
				}
			}
		}
		if (CollectionUtil.isEmpty(list)){
			return null;
		}
		return "经理人该年度已填报";
	}


	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus  更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus,String comment) {
		try {
			BaseBusinessIndicators baseBusinessIndicators = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				baseBusinessIndicators.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				baseBusinessIndicators.setApprovedTime(now);
			}
			if (StringUtil.isNotBlank(baseBusinessIndicators.getDataSource()) &&
					StringUtil.isNotBlank(baseBusinessIndicators.getDataSourceId())){
				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
					ApprovalMessage approvalMessage = new ApprovalMessage();
					approvalMessage.setDataSourceId(baseBusinessIndicators.getDataSourceId());
					approvalMessage.setOpinion(comment);
					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
					approvalMessage.setIsSend(1);
					approvalMessage.setDataSourceType(GZW_TYPE);

					if (baseBusinessIndicators.getDataSource().equals(YthConstant.DATA_NINGBO)) {
						approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
						approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
						approvalMessage.setFormType(FormTypeConstant.MANAGEMENT_PERFORMANCE);
						approvalMessage.setFilingCode(baseBusinessIndicators.getCode());
					}
					approvalMessageService.save(approvalMessage);
				}
			}
			baseBusinessIndicators.setStatus(updateStatus);
			updateById(baseBusinessIndicators);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}


	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<BaseBusinessIndicators> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(BaseBusinessIndicators::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<BaseBusinessIndicators> baseBusinessIndicators = list(queryWrapper);
		List<BaseBusinessIndicatorsVO> baseBusinessIndicatorsVOS = baseBusinessIndicatorsWrapper.entityToVO(baseBusinessIndicators);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(baseBusinessIndicatorsVOS)){
				for (BaseBusinessIndicatorsVO vo : baseBusinessIndicatorsVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFillingUnitName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillingUnitId());
					pd.put("formType", FormTypeConstant.MANAGEMENT_PERFORMANCE);
					pd.put("orgName", vo.getFillingUnitName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.MANAGEMENT_PERFORMANCE);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(BaseBusinessIndicators baseBusinessIndicators) {
		baseBusinessIndicators.setModuleType(2);
		boolean result = saveOrUpdate(baseBusinessIndicators);
		if (result){
			if (baseBusinessIndicators.getDocList()!=null) {
				fileService.edit(baseBusinessIndicators.getId().toString(), baseBusinessIndicators.getDocList());
			}
			List<BusinessIndicators> businessIndicatorsList = baseBusinessIndicators.getBaseIndicators();
			List<BusinessIndicators> list1 = baseBusinessIndicators.getCategoryIndicators();
			List<BusinessIndicators> list2 = baseBusinessIndicators.getIndustryIndicators();
			List<BusinessIndicators> list3 = baseBusinessIndicators.getOtherIndicators();
			if (CollectionUtil.isNotEmpty(businessIndicatorsList)){
				if(CollectionUtil.isNotEmpty(list1)) businessIndicatorsList.addAll(list1);
				if(CollectionUtil.isNotEmpty(list2)) businessIndicatorsList.addAll(list2);
				if(CollectionUtil.isNotEmpty(list3)) businessIndicatorsList.addAll(list3);
				for (BusinessIndicators businessIndicators : businessIndicatorsList){
					if (businessIndicators.getId() != null &&
							Optional.ofNullable(businessIndicators.getIsDeleted()).isPresent() && businessIndicators.getIsDeleted().intValue() == 1) {
						businessIndicatorsService.removeById(businessIndicators.getId());
					}else {
						businessIndicators.setBaseBusinessIndicatorsId(baseBusinessIndicators.getId());
						businessIndicatorsService.saveOrUpdate(businessIndicators);
					}
				}
			}
			List<TaskIndicators> taskIndicators = baseBusinessIndicators.getTaskIndicators();
			if (CollectionUtil.isNotEmpty(taskIndicators)){
				for (TaskIndicators taskIndicator : taskIndicators){
					if (taskIndicator.getId() != null &&
							Optional.ofNullable(taskIndicator.getIsDeleted()).isPresent() && taskIndicator.getIsDeleted().intValue() == 1) {
						taskIndicatorsService.removeById(taskIndicator.getId());
					}else {
						taskIndicator.setBaseBusinessIndicatorsId(baseBusinessIndicators.getId());
						taskIndicatorsService.saveOrUpdate(taskIndicator);
					}
				}
			}

			List<MajorProject> majorProjects = baseBusinessIndicators.getMajorProjects();
			if (CollectionUtil.isNotEmpty(majorProjects)){
				for (MajorProject majorProject : majorProjects){
					if (majorProject.getId() != null &&
							Optional.ofNullable(majorProject.getIsDeleted()).isPresent() && majorProject.getIsDeleted().intValue() == 1) {
						majorProjectService.removeById(majorProject.getId());
					}else {
						majorProject.setBaseBusinessIndicatorsId(baseBusinessIndicators.getId());
						majorProjectService.saveOrUpdate(majorProject);
					}
				}
			}

			List<MainBusiness> mainBusinesses = baseBusinessIndicators.getMainBusinesses();
			if (CollectionUtil.isNotEmpty(mainBusinesses)){
				for (MainBusiness mainBusiness : mainBusinesses){
					if (mainBusiness.getId() != null &&
							Optional.ofNullable(mainBusiness.getIsDeleted()).isPresent() && mainBusiness.getIsDeleted().intValue() == 1) {
						mainBusinessService.removeById(mainBusiness.getId());
					}else {
						mainBusiness.setBaseBusinessIndicatorsId(baseBusinessIndicators.getId());
						mainBusinessService.saveOrUpdate(mainBusiness);
					}
				}
			}

		}
		return result;
	}

	@Override
	public R<BaseBusinessIndicatorsVO> getDetailObj(BaseBusinessIndicatorsVO baseBusinessIndicatorsVO) {
		if(!Optional.ofNullable(baseBusinessIndicatorsVO).isPresent()){
			return new R(CommonCode.FAIL);
		}
		List<BusinessIndicatorsVO> businessIndicatorsVOS = businessIndicatorsWrapper
				.entityToVO(businessIndicatorsService.list(new LambdaQueryWrapper<BusinessIndicators>()
						.eq(BusinessIndicators::getBaseBusinessIndicatorsId, baseBusinessIndicatorsVO.getId())));
//		if (CollectionUtil.isNotEmpty(businessIndicatorsVOS)){
//			businessIndicatorsService.setBusinessName(businessIndicatorsVOS);
//		}
		baseBusinessIndicatorsVO.setBusinessIndicatorsVOS(businessIndicatorsVOS);

		List<TaskIndicatorsVO> taskIndicatorsVOS = taskIndicatorsWrapper
				.entityToVO(taskIndicatorsService.list(new LambdaQueryWrapper<TaskIndicators>()
						.eq(TaskIndicators::getBaseBusinessIndicatorsId, baseBusinessIndicatorsVO.getId())));
		if (CollectionUtil.isNotEmpty(taskIndicatorsVOS)){
			taskIndicatorsService.setTaskName(taskIndicatorsVOS);
		}
		baseBusinessIndicatorsVO.setTaskIndicatorsVOS(taskIndicatorsVOS);

		List<MajorProject> majorProjects = majorProjectService.list(new LambdaQueryWrapper<MajorProject>().eq(MajorProject::getBaseBusinessIndicatorsId, baseBusinessIndicatorsVO.getId()));
		baseBusinessIndicatorsVO.setMajorProjects(majorProjects);

		List<MainBusiness> mainBusinesses = mainBusinessService.list(new LambdaQueryWrapper<MainBusiness>().eq(MainBusiness::getBaseBusinessIndicatorsId, baseBusinessIndicatorsVO.getId()));
		baseBusinessIndicatorsVO.setMainBusinesses(mainBusinesses);

		R<BaseBusinessIndicatorsVO> objResult = new R<>(CommonCode.SUCCESS);
		objResult.setPageData(baseBusinessIndicatorsVO);
		return objResult;
	}

	@Override
	public void goBackToStash(String formId) {
		Long id = Long.valueOf(formId);
		List<BaseBusinessIndicators> baseBusinessIndicators = list(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getInitialId, id).eq(BaseBusinessIndicators::getModuleType,2));
		if (CollectionUtil.isNotEmpty(baseBusinessIndicators) && baseBusinessIndicators.size() > 1){
			throw new MyRuntimeException(new ObjResult("该绩效目标已进行其他操作，无法退回！"));
		}
		BaseBusinessIndicators indicators = getById(id);
		if (indicators.getStatus() == FormStatusConstant.FINISH){
			LambdaUpdateWrapper<BaseBusinessIndicators> updateWrapper = new LambdaUpdateWrapper<>();
			update(updateWrapper.eq(BaseBusinessIndicators::getId, id)
					.set(BaseBusinessIndicators::getApprovedUser, null).set(BaseBusinessIndicators::getApprovedTime, null)
					.set(BaseBusinessIndicators::getIndicatorStatus, null));
		}
		handleStatus(Long.valueOf(formId), UNREVIEWED, null);
	}

	@Override
	public BaseBusinessIndicatorsVO getDetailByMonth(String fillingMonth,String fillingUnitId){
		String year = fillingMonth.split("-")[0];
		List<BaseBusinessIndicators> list = list(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getFillingYear, year).eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId).eq(BaseBusinessIndicators::getIsLatest,2)
				.eq(BaseBusinessIndicators::getStatus,3).eq(BaseBusinessIndicators::getModuleType,2));
		if (CollectionUtil.isNotEmpty(list)){
			BaseBusinessIndicatorsVO baseBusinessIndicatorsVO = baseBusinessIndicatorsWrapper.entityToVO(list.get(0));
			return getDetailObj(baseBusinessIndicatorsVO).getPageData();
		}
		return null;
	}

	@Override
	public BaseBusinessIndicatorsVO getDetailByDto(String fillingYear,String fillingUnitId){
		List<BaseBusinessIndicators> list = list(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getFillingYear, fillingYear).eq(BaseBusinessIndicators::getModuleType,2)
				.eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId).eq(BaseBusinessIndicators::getIsLatest,2).eq(BaseBusinessIndicators::getStatus,3));
		if (CollectionUtil.isNotEmpty(list)){
			BaseBusinessIndicatorsVO baseBusinessIndicatorsVO = baseBusinessIndicatorsWrapper.entityToVO(list.get(0));
			return getDetailObj(baseBusinessIndicatorsVO).getPageData();
		}
		return null;
	}

	@Override
	public BaseBusinessIndicators findLatestByInitialId(Long initialId) {
		return getOne(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getInitialId, initialId)
				.eq(BaseBusinessIndicators::getIsLatest, 2).eq(BaseBusinessIndicators::getModuleType,2));
	}

	@Override
	public ListResult<BaseBusinessIndicatorsVO> versionList(Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("version");
		}
		QueryWrapper<BaseBusinessIndicators> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseBusinessIndicators()), entityList
		);
		queryWrapper.eq("module_type",2);
		IPage<BaseBusinessIndicators> pages = page(Condition.getPage(query), queryWrapper);
		List<BaseBusinessIndicatorsVO> baseBusinessIndicatorsVOS = baseBusinessIndicatorsWrapper.entityToVO(pages.getRecords());
		ListResult<BaseBusinessIndicatorsVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseBusinessIndicatorsVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	@Override
	public List<BaseBusinessIndicators> getSourceData(){
		List<BaseBusinessIndicators> list = list(Wrappers.<BaseBusinessIndicators>lambdaQuery().eq(BaseBusinessIndicators::getDataSource, YthConstant.DATA_NINGBO).eq(BaseBusinessIndicators::getModuleType,2));
		if (CollectionUtil.isNotEmpty(list)){
			List<Long> ids = list.stream().map(BaseBusinessIndicators::getId).collect(Collectors.toList());
			List<BusinessIndicators> businessIndicators = businessIndicatorsService.list(Wrappers.<BusinessIndicators>lambdaQuery().in(BusinessIndicators::getBaseBusinessIndicatorsId, ids));
			List<TaskIndicators> taskIndicators = taskIndicatorsService.list(Wrappers.<TaskIndicators>lambdaQuery().in(TaskIndicators::getBaseBusinessIndicatorsId, ids));
			List<MajorProject> majorProjects = majorProjectService.list(Wrappers.<MajorProject>lambdaQuery().in(MajorProject::getBaseBusinessIndicatorsId, ids));
			List<MainBusiness> mainBusinesses = mainBusinessService.list(Wrappers.<MainBusiness>lambdaQuery().in(MainBusiness::getBaseBusinessIndicatorsId, ids));
			list.forEach( indicator ->{
				Long id = indicator.getId();
				if (CollectionUtil.isNotEmpty(businessIndicators)){
					indicator.setBusinessIndicators(businessIndicators.stream().filter(m -> id.equals(m.getBaseBusinessIndicatorsId())).collect(Collectors.toList()));
				}
				if (CollectionUtil.isNotEmpty(taskIndicators)){
					indicator.setTaskIndicators(taskIndicators.stream().filter(m -> id.equals(m.getBaseBusinessIndicatorsId())).collect(Collectors.toList()));
				}
				if (CollectionUtil.isNotEmpty(majorProjects)){
					indicator.setMajorProjects(majorProjects.stream().filter(m -> id.equals(m.getBaseBusinessIndicatorsId())).collect(Collectors.toList()));
				}
				if (CollectionUtil.isNotEmpty(mainBusinesses)){
					indicator.setMainBusinesses(mainBusinesses.stream().filter(m -> id.equals(m.getBaseBusinessIndicatorsId())).collect(Collectors.toList()));
				}
			});
		}
		return list;
	}

	@Override
	public String saveBaseBusiness(String data) {
		YthResult ythResult = new YthResult();
		//成功的id集合
		List<String> successIds = new ArrayList<>();
		//失败的id集合
		List<String> failIds = new ArrayList<>();
		//失败的原因
		List<String> failReasons = new ArrayList<>();
		//将json字符串转换成list
		List<BaseBusinessIndicators> dataList = JSON.parseArray(data, BaseBusinessIndicators.class);

		if (CollectionUtil.isNotEmpty(dataList)) {
			Map<String, String> orgSourceMap = orgService.getSourceId();
			List<ProjectInfo> projectInfos = projectInfoService.list(new LambdaQueryWrapper<ProjectInfo>().eq(ProjectInfo::getDataSource, 3));
			//code
			List<AppraisalIndex> indexList = appraisalIndexService.listByTableCode("001");
			//根据datasourceIds 查询出所有的数据
			List<BaseBusinessIndicators> list = list(new LambdaQueryWrapper<BaseBusinessIndicators>().in(BaseBusinessIndicators::getDataSourceId, dataList.stream().map(BaseBusinessIndicators::getDataSourceId).toArray()).eq(BaseBusinessIndicators::getStatus, UNREVIEWED).eq(BaseBusinessIndicators::getModuleType,2));

			if (CollectionUtil.isNotEmpty(list)) {
				//删除子集
				List<Long> ids = list.stream().map(BaseBusinessIndicators::getId).collect(Collectors.toList());
				businessIndicatorsService.deleteByParentId(ids);
				taskIndicatorsService.deleteByParentId(ids);
				majorProjectService.deleteByParentId(ids);
				mainBusinessService.deleteByParentId(ids);
			}
			for (BaseBusinessIndicators entity:dataList){
				transfer(entity,orgSourceMap,indexList,projectInfos);
				//id重复略过
				if (CollectionUtil.isNotEmpty(list)){
					List<String> olIds = list.stream().map(BaseBusinessIndicators::getDataSourceId).collect(Collectors.toList());
					String dataSourceId = entity.getDataSourceId();
					//判断数据库中是否有数据
					if (olIds.contains(dataSourceId)){
						for (BaseBusinessIndicators oldEntity:list){
							if (dataSourceId.equals(oldEntity.getDataSourceId())){
								//判断status是否为0，如果是0，就更新，不是0，就不更新
								if (CheckStatus.checkCode(oldEntity.getStatus())){
									successIds.add(dataSourceId);
									entity.setId(oldEntity.getId());
									entity.setDataSource(YthConstant.DATA_NINGBO);
									submit(entity);
									list.remove(oldEntity);
									break;
								}else {
									failIds.add(dataSourceId);
									failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
									break;
								}
							}
						}
					}else {
						//如果数据库中没有数据，就新增
						entity.setDataSource(YthConstant.DATA_NINGBO);
						submit(entity);
						successIds.add(entity.getDataSourceId());
					}
				}else {
					//如果数据库中没有数据，就新增
					entity.setDataSource(YthConstant.DATA_NINGBO);
					submit(entity);
					successIds.add(entity.getDataSourceId());
				}
			}
		}else {
			failReasons.add("数据为空");
		}
		ythResult.setSuccessIds(successIds);
		ythResult.setFailIds(failIds);
		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
		//ythResult转换成json字符串
		return JSON.toJSONString(ythResult);
	}

	private void transfer(BaseBusinessIndicators entity, Map<String, String> orgSourceMap,List<AppraisalIndex> indexList
			,List<ProjectInfo> projectInfos){
		Optional.ofNullable(entity.getFillingUnitId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					if (StringUtil.isNotBlank(orgId)){
						entity.setFillingUnitId(orgId);
						entity.setCreateCompanyId(orgId);
					}
				}
		);
		//转换code
		List<BusinessIndicators> businessIndicators = entity.getBaseIndicators();
		List<BusinessIndicators> list1 = entity.getCategoryIndicators();
		List<BusinessIndicators> list2 = entity.getIndustryIndicators();
		List<BusinessIndicators> list3 = entity.getOtherIndicators();
		if (CollectionUtil.isNotEmpty(businessIndicators)){
			if(CollectionUtil.isNotEmpty(list1)) businessIndicators.addAll(list1);
			if(CollectionUtil.isNotEmpty(list2)) businessIndicators.addAll(list2);
			if(CollectionUtil.isNotEmpty(list3)) businessIndicators.addAll(list3);
			businessIndicators.forEach( bus ->{
				bus.setDataSource(YthConstant.DATA_NINGBO);
				if (Optional.ofNullable(bus.getIndicatorsCode()).isPresent()){
					if ("KH7".equals(bus.getIndicatorsCode())){
						indexList.stream().filter(m ->m.getType() == 1 && m.getFlag() == 2).findFirst().ifPresent(code ->{
							bus.setIndicatorsCategoryId(code.getId());
						});
					}else {
						indexList.stream().filter(m ->bus.getIndicatorsCode().equals(m.getCompleteCode())).findFirst().ifPresent(code ->{
							bus.setIndicatorsCategoryId(code.getId());
							bus.setIndicatorsCategoryName(code.getName());
						});
					}
				}
			});
		}
		List<TaskIndicators> taskIndicators = entity.getTaskIndicators();
		if (CollectionUtil.isNotEmpty(taskIndicators)){
			taskIndicators.forEach( task ->{
				task.setDataSource(YthConstant.DATA_NINGBO);
				if (Optional.ofNullable(task.getIndicatorsCode()).isPresent()){
					if ("ZDRW".equals(task.getIndicatorsCode())){
						indexList.stream().filter(m ->m.getType() == 2 && m.getSort() == 1).findFirst().ifPresent(code ->{
							task.setIndicatorsCategoryId(code.getId());
						});
					}else if ("LSRW".equals(task.getIndicatorsCode())){
						indexList.stream().filter(m ->m.getType() == 2 && m.getSort() == 2).findFirst().ifPresent(code ->{
							task.setIndicatorsCategoryId(code.getId());
						});
					}
				}
			});
		}

		List<MajorProject> majorProjects = entity.getMajorProjects();
		if (CollectionUtil.isNotEmpty(majorProjects)){
			majorProjects.forEach(project ->{
				project.setDataSource(YthConstant.DATA_NINGBO);
				if (Optional.ofNullable(project.getDataProjectId()).isPresent()){
					projectInfos.stream().filter(m -> project.getDataProjectId().equals(m.getDataSourceId())).findFirst().ifPresent(proInfo ->{
						project.setProjectId(proInfo.getId());
						project.setProjectName(proInfo.getProjectName());
					});
				}
			});
		}
		List<MainBusiness> mainBusinesses = entity.getMainBusinesses();
		if (CollectionUtil.isNotEmpty(mainBusinesses)){
			mainBusinesses.forEach(main ->{
				main.setDataSource(YthConstant.DATA_NINGBO);
			});
		}
	}

}